#include "chanlist.h"
#include "components/board.h"

namespace Wishmaster
{
	ChanList::ChanList(QObject *parent) :
		QObject(parent)
	{
	}

	ChanList::~ChanList()
	{
		clear();
	}

	void ChanList::addChan(Chan* chan)
	{
		// TODO check for double-adding
		m_chans.push_back(chan);
	}

	void ChanList::removeChan(Chan* chan)
	{
		for(std::vector<Chan*>::iterator it = m_chans.begin(); it != m_chans.end(); ++it)
		{
			if((*it) == chan)
			{
				delete (*it);
				m_chans.erase(it);
				return;
			}
		}
	}

	Chan* ChanList::getChan(const QString& host) const
	{
		foreach(Chan* chan, m_chans)
		{
			if(chan->getHost() == host)
				return chan;
		}
		return NULL;
	}

	Chan* ChanList::getChan(int number) const
	{
		if(number < 0 || number >= (int)m_chans.size())
			return 0;
		return m_chans.at(number);
	}

	int ChanList::chansCount() const
	{
		return m_chans.size();
	}

	void ChanList::saveAll()
	{
		for(int i = 0; i < chansCount(); i++)
		{
			getChan(i)->save();
		}
	}

	void ChanList::clear()
	{
		for(int i = 0; i < chansCount(); i++)
		{
			getChan(i)->save();
			delete getChan(i);
		}
		m_chans.clear();
	}

	Board* ChanList::getBoard(const QString& chanName, const QString& boardId) const
	{
		Chan* chan = getChan(chanName);
		if(!chan)
			return NULL;
		return chan->board(boardId);
	}

	ThreadPtr ChanList::getThread(const ThreadId& id) const
	{
		Board* b = getBoard(id.chanName(), id.boardId());
		return b->getThread(id);
	}

	PostPtr ChanList::getPost(const PostId& id) const
	{
		ThreadPtr thread = getThread(id.getThreadId());
		return thread->lookupPost(id);
	}
}
